package com.tmpt.controller.taglib;

import com.tmpt.dto.*;
import com.tmpt.service.ITemplateService;
import com.tmpt.utils.JsonMap;
import com.tmpt.utils.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TemplateTag {

	private Logger log = Logger.getLogger(this.getClass());


	@Resource(name="pageContext") PageContext pageContext;
	@Resource(name="templateService") private ITemplateService templateService;



	public Map<String,Object> getColumnList(Map<String,String> paramMap){
		UrlAuthUtils urlAuthUtils = new UrlAuthUtils((HttpServletRequest)pageContext.getRequest());
		String keyRandom = paramMap.get("keyRandom");
		String add_editUrl = paramMap.get("add_editUrl");
		String removeUrl = paramMap.get("removeUrl");
		String reportUrl = paramMap.get("reportUrl");


		//取列属性相关数据
		Result resultObj = getDbColumnProperty(keyRandom);
		Map<String,Map<String,String>> dbcolumnsProperty = (Map<String,Map<String,String>>)resultObj.getResultMap().get("dbcolumnsProperty");
		//Map<String,String> columnAliasMap = (Map<String,String>)resultObj.getResultMap().get("columnAliasMap");
		//Map<String,String> columnTableMap = (Map<String,String>)resultObj.getResultMap().get("columnTableMap");

		A1TemplateTableDto templateTable = templateService.getTemplateTable(keyRandom);
		List<A1TemplateColumnDto> columnList = templateTable.getA1TemplateColumnDtoList();
		int hasCheckbox = templateTable.getHasCheckbox();
		
		List<A1TemplateColumnDto> column4Add = new ArrayList<A1TemplateColumnDto>();//add and edit dialog
		JSONArray jarrColumn = new JSONArray();
		JSONArray jarrColumn_frozen = new JSONArray();
		JSONObject defaultValueJO = new JSONObject();
		//checkbox框
		if(hasCheckbox == 1){
			JSONObject jo = new JSONObject();
			jo.put("field", "ck");
			jo.put("checkbox", "true");
			jarrColumn.put(jo);
		}
		for(A1TemplateColumnDto a1TemplateColumnDto:columnList){
			String columnName = a1TemplateColumnDto.getColumnName();
			String columnShowName = a1TemplateColumnDto.getColumnShowName();
			String columnTip = a1TemplateColumnDto.getColumnTip();
			int dataResource = a1TemplateColumnDto.getDataResource();
			int isFrozenColumn = a1TemplateColumnDto.getIsFrozenColumn();
			int isHidden = a1TemplateColumnDto.getIsHidden();
			int canAdd = a1TemplateColumnDto.getCanAdd();
			int columnWidth = a1TemplateColumnDto.getColumnWidth();
			int isSortColumn = a1TemplateColumnDto.getIsSortColumn();
			//列在DB中的类型
			/*System.out.println("======>columnName:"+columnName);
			String dbColumnDataType = "";
			String dbcolumnsPropertyKey = columnTableMap.get(columnName)+"_"+columnName;
			Map<String,String> dbColumnPropertyMap = dbcolumnsProperty.get(dbcolumnsPropertyKey);
			if(dbColumnPropertyMap!=null){
				dbColumnDataType = dbColumnPropertyMap.get("data_type");
			}*/
			/*if(isHidden==1){ //可能是主键ID,页面不展示
				continue;
			}*/
			if(isFrozenColumn == 1){
				JSONObject jo_frozen = new JSONObject();
				//列类型是datetime\date\timestamp时，服务层对结果集中添加了转换后数据，模式：createdate -> createdate_Str
				//列是combobox时，同上，目前是select语句中处理的case when （20170909）
				if(/*dbColumnDataType.equals("date")
						|| dbColumnDataType.equals("datetime")
						|| dbColumnDataType.equals("timestamp")
						||*/
						dataResource == A1TemplateColumnDto.dataResource_OptionsTable
						/*|| dataResource == A1TemplateColumnDto.dataResource_Sql*///公司id, 公司name, 公司id不显示
						|| dataResource == A1TemplateColumnDto.dataResource_ColumnOptionData){//Enum中取数据，model中列加了_Str，取显示，如：deleteflag_Str
					//加上，编辑时可能用
					JSONObject jo1 = new JSONObject();
					jo1.put("field", columnName);
					jo1.put("title", columnShowName);
					jo1.put("hidden", "true");
					jarrColumn_frozen.put(jo1);
					//
					jo_frozen.put("field", columnName+"_Str");
				}else {
					jo_frozen.put("field", columnName);
				}
				jo_frozen.put("title", columnShowName);
				if(columnWidth!=0){
					jo_frozen.put("width", columnWidth);
				}else{
					jo_frozen.put("width", 100);
				}
				if(isSortColumn == 1){
					jo_frozen.put("sortable", "true");
				}
				if(isHidden==1){ //可能是主键ID,页面不展示
					jo_frozen.put("hidden", "true");
				}
				
				jarrColumn_frozen.put(jo_frozen);
			}else{
				JSONObject jo = new JSONObject();
				//列类型是datetime\date\timestamp时，服务层对结果集中添加了转换后数据，模式：createdate -> createdate_Str
				//列是combobox时，同上，目前是select语句中处理的case when （20170909）
				if(/*dbColumnDataType.equals("date")
						|| dbColumnDataType.equals("datetime")
						|| dbColumnDataType.equals("timestamp")
						|| */dataResource == A1TemplateColumnDto.dataResource_OptionsTable
						/*|| dataResource == A1TemplateColumnDto.dataResource_Sql*///公司id, 公司name, 公司id不显示
						|| dataResource == A1TemplateColumnDto.dataResource_ColumnOptionData){//Enum中取数据，model中列加了_Str，取显示，如：deleteflag_Str
					//加上，编辑时可能用
					JSONObject jo1 = new JSONObject();
					jo1.put("field", columnName);
					jo1.put("title", columnShowName);
					jo1.put("hidden", "true");
					jarrColumn.put(jo1);
					//
					jo.put("field", columnName+"_Str");
				}else {
					jo.put("field", columnName);
				}
				jo.put("title", columnShowName);
				if(columnWidth!=0){
					jo.put("width", columnWidth);
				}else {
					jo.put("width", 100);
				}
				if(isSortColumn == 1){
					jo.put("sortable", "true");
				}
				if(isHidden==1){ //可能是主键ID,页面不展示
					jo.put("hidden", "true");
				}
				jarrColumn.put(jo);
			}

			List<A1TemplateColumnDto> templateTableColumnOptionList = templateService.getTemplateTableColumnOptionList(keyRandom);

			for(A1TemplateColumnDto dtoTmp : templateTableColumnOptionList){
				String columnNameTmp = dtoTmp.getColumnName();
				if(columnNameTmp.equals(columnName)){
					a1TemplateColumnDto.setA1TemplateColumnOptionJsonArray(dtoTmp.getA1TemplateColumnOptionJsonArray());
					break;
				}
			}
			if(canAdd == 1){
				column4Add.add(a1TemplateColumnDto);
			}

			//Default value
			String defaultValue = a1TemplateColumnDto.getDefaultValue();
			if(!StringUtils.isNull(defaultValue)) {
				defaultValueJO.put(columnName, defaultValue);
			}
		}

		
		//行尾Button
		//jsonObject
		JSONObject joOpt = new JSONObject();
		joOpt.put("field", "opt");
		joOpt.put("title", "操作");
		joOpt.put("align", "center");
		//
		StringBuilder sbLineTail = new StringBuilder();
		sbLineTail.append("function(value,rowData,rowIndex){");
		sbLineTail.append("if(typeof(rowData.id) == 'undefined'){return '';};");
		sbLineTail.append("var btn = '';");
		int buttonCount = 0;
		//行尾BUTTON
		List<A1TemplateLineTailMenuDto> lineTailMenuDtoList = templateTable.getA1TemplateLineTailMenuDtoList();
		for(A1TemplateLineTailMenuDto lineTailMenuDto : lineTailMenuDtoList){
			String itemName = lineTailMenuDto.getItemName();
			String url = lineTailMenuDto.getUrl();
			int isDialog = lineTailMenuDto.getIsDialog();
			int width = lineTailMenuDto.getWidth();
			int height  = lineTailMenuDto.getHeight();
			if(urlAuthUtils.authorizeUsingUrlCheck(url)) {
				String function = "btn += '<a class=\"editcls\" style=\"height:20px;\"  onclick=lineTailBtnOnClick(\"##1\",\"##2\",\"##3\",\"##4\",\"##5\",'+rowIndex+') href=\"javascript:void(0)\">##6</a>';";
				function = function.replace("##1", url);
				function = function.replace("##2", String.valueOf(isDialog));
				function = function.replace("##3", String.valueOf(width));
				function = function.replace("##4", String.valueOf(height));
				function = function.replace("##5", itemName);
				function = function.replace("##6", itemName);
				sbLineTail.append(function);
				buttonCount++;
			}
		}
		//是否有Edit button
		if(templateTable.getHasEditBtn() == 1){
			if(urlAuthUtils.authorizeUsingUrlCheck(add_editUrl)) {
				buttonCount++;
				sbLineTail.append("btn += '<a class=\"editcls\" style=\"height:20px;\" onclick=\"editRow('+rowIndex+')\" href=\"javascript:void(0)\">编辑</a>';");
			}
		}
		if(templateTable.getHasEditBtn() == 2){
			if(urlAuthUtils.authorizeUsingUrlCheck(add_editUrl)) {
				buttonCount++;
				sbLineTail.append("btn += '<a class=\"editcls\" style=\"height:20px;\" onclick=\"editRow('+rowIndex+')\" href=\"javascript:void(0)\">编辑</a>';");
			}
			if(urlAuthUtils.authorizeUsingUrlCheck(removeUrl)) {
				buttonCount++;
				sbLineTail.append("btn += '<a class=\"delcls\" style=\"height:20px;\" onclick=\"removeRow('+rowIndex+')\" href=\"javascript:void(0)\">删除</a>';");
			}
		}
		if(templateTable.getHasEditBtn() == 3){
			if(urlAuthUtils.authorizeUsingUrlCheck(removeUrl)) {
				buttonCount++;
				sbLineTail.append("btn += '<a class=\"delcls\" style=\"height:20px;\" onclick=\"removeRow('+rowIndex+')\" href=\"javascript:void(0)\">删除</a>';");
			}
		}
		//是否有History button
		/*if(templateTable.getHasHistoryBtn() == 1){
			buttonCount++;
			sbLineTail.append("btn += '<a class=\"delcls\" onclick=\"historyRow('+rowIndex+')\" href=\"javascript:void(0)\">历史</a>';");
		}*/
		sbLineTail.append("return btn;}");
		if(buttonCount != 0){
			joOpt.put("width", buttonCount*70+20);
		}
		System.out.println(sbLineTail.toString());
		joOpt.put("formatter", "#"+sbLineTail.toString()+"$");
		jarrColumn.put(joOpt);
		String jarrColumnStr = jarrColumn.toString();
		jarrColumnStr = jarrColumnStr.replace("\"#", "").replace("$\"", "");


		Map<String,Object> map = new HashMap<String, Object>();
		map.put("columns", jarrColumnStr);
		map.put("frozenColumns", jarrColumn_frozen.toString());
		map.put("column4Add", column4Add);
		map.put("toolbarBtns", getToolbarBtns(templateTable, urlAuthUtils, add_editUrl, reportUrl));
		map.put("defaultValueJOStr", defaultValueJO.toString());
		map.put("rightMenuContext",templateTable.getA1TemplateRightMenuDtoList());
		map.put("conditionColumnList",getConditionColumnList(keyRandom, templateTable));
		map.put("templateTable",templateTable);


		return map;
	}


	private Result getDbColumnProperty(String keyRandom){
		//取数据库列类型和table的alias（Map<String,String>）
		Map<String,String[]> paramMap = new HashMap<String, String[]>();
		paramMap.put("_keyRandom",new String[]{keyRandom});
		//map to jsonstring
		String paramJson = JsonMap.map2Json(paramMap);
		Result resultObj = null;
		try {
			resultObj = templateService.genSql4DynamicDS(paramJson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultObj;
	}

	/**
	 * 取查询条件列表
	 * //@param paramMap
	 * @return
	 * */
	//public List<A1TemplateColumnDto> getConditionColumnList(Map<String,String> paramMap){
	private List<A1TemplateColumnDto> getConditionColumnList(String keyRandom,A1TemplateTableDto templateTable){

		//String keyRandom = paramMap.get("keyRandom");

		//取列属性相关数据
		Result resultObj = getDbColumnProperty(keyRandom);
		Map<String,Map<String,String>> dbcolumnsProperty = (Map<String,Map<String,String>>)resultObj.getResultMap().get("dbcolumnsProperty");
		Map<String,String> columnAliasMap = (Map<String,String>)resultObj.getResultMap().get("columnAliasMap");
		Map<String,String> columnTableMap = (Map<String,String>)resultObj.getResultMap().get("columnTableMap");

		//A1TemplateTableDto templateTable = getTemplateTable(keyRandom);
		List<A1TemplateColumnDto> a1TemplateColumnDtoRemoveList = new ArrayList<A1TemplateColumnDto>();
		List<A1TemplateColumnDto> a1TemplateColumnDtoList = templateTable.getA1TemplateColumnDtoList();
		List<A1TemplateColumnDto> a1TemplateColumnDtoListCopy = new ArrayList<A1TemplateColumnDto>();
		a1TemplateColumnDtoListCopy.addAll(a1TemplateColumnDtoList);

		for(A1TemplateColumnDto a1TemplateColumnDto : a1TemplateColumnDtoListCopy){

			//列在DB中的类型
			String columnName = a1TemplateColumnDto.getColumnName();
			System.out.println("=====1>columnName:"+columnName);
			String dbColumnDataType = "";
			String dbcolumnsPropertyKey = columnTableMap==null?"":columnTableMap.get(columnName)+"_"+columnName;
			System.out.println("------>:"+dbcolumnsProperty);
			Map<String,String> dbColumnPropertyMap = dbcolumnsProperty.get(dbcolumnsPropertyKey);
			if(dbColumnPropertyMap!=null){
				dbColumnDataType = dbColumnPropertyMap.get("data_type");
			}
			//column db type, 重加载为数据库中的值
			a1TemplateColumnDto.setColumnDataType(dbColumnDataType);

			//查询框中提示内容
			String queryTypePlaceholder = "";
			String queryType = a1TemplateColumnDto.getQueryType();
			if(!StringUtils.isNull(queryType)) {
				if (queryType.contains("like")) {
					queryTypePlaceholder = "模糊查询";
				}
			}
			a1TemplateColumnDto.setQueryTypePlaceholder(queryTypePlaceholder);


			//不是查询条件
			if(a1TemplateColumnDto.getIsQuery() == 0){
				a1TemplateColumnDtoRemoveList.add(a1TemplateColumnDto);
				continue;
			}
			if(a1TemplateColumnDto.getA1TemplateColumnOptionDtoList().size()>0){
				//是多选项，页面显示select
				a1TemplateColumnDto.setHasOptions(1);
				//加“全部”
				String keyNameDefault = "";
				String valueNameDefault = "全部";
				A1TemplateColumnOptionDto optionDto = new A1TemplateColumnOptionDto();
				optionDto.setKeyName(keyNameDefault);
				optionDto.setValueName(valueNameDefault);
				a1TemplateColumnDto.getA1TemplateColumnOptionDtoList().add(0, optionDto);

			}else{
				//是单选项，页面显示input
				a1TemplateColumnDto.setHasOptions(0);
			}
		}
		a1TemplateColumnDtoListCopy.removeAll(a1TemplateColumnDtoRemoveList);
		return a1TemplateColumnDtoListCopy;
	}

	/**
	 * 工具栏button
	 * @param templateTable
	 * @return
	 */
	private String getToolbarBtns(A1TemplateTableDto templateTable,UrlAuthUtils urlAuthUtils,String add_editUrl,String reportUrl){

		StringBuilder sb = new StringBuilder();
		List<A1TemplateToolbarBtnDto> a1TemplateToolbarBtnDtoList = templateTable.getA1TemplateToolbarBtnDtoList();
		
		sb.append("toolbar:[");
		//是否有添加button
		if(templateTable.getHasAddBtn() == 1){
			if(urlAuthUtils.authorizeUsingUrlCheck(add_editUrl)) {
				sb.append("{");
				sb.append("text:'添加',");
				sb.append("iconCls:'icon-add',");
				sb.append("handler:function(){toolbar_add();}");
				sb.append("},");
			}
		}

		//是否有报表下载button
		if(templateTable.getHasDownloadReportBtn() == 1){
			if(urlAuthUtils.authorizeUsingUrlCheck(reportUrl)) {
				sb.append("{");
				sb.append("text:'报表下载',");
				sb.append("iconCls:'icon-save',");
				sb.append("handler:function(){downloadReport();}");
				sb.append("},");
			}
		}
		for(A1TemplateToolbarBtnDto a1TemplateToolbarBtnDto:a1TemplateToolbarBtnDtoList){
			String itemName = a1TemplateToolbarBtnDto.getItemName();
			String url = a1TemplateToolbarBtnDto.getUrl();
			int isDialog = a1TemplateToolbarBtnDto.getIsDialog();
			int width = a1TemplateToolbarBtnDto.getWidth();
			int height  = a1TemplateToolbarBtnDto.getHeight();
			String function = "function(){toolbarBtnOnClick('##1','##2','##3','##4','##5');}";
			function = function.replace("##1", url);
			function = function.replace("##2", String.valueOf(isDialog));
			function = function.replace("##3", String.valueOf(width));
			function = function.replace("##4", String.valueOf(height));
			function = function.replace("##5", itemName);
			
			sb.append("{");
			sb.append("text:'").append(itemName).append("',");
			sb.append("iconCls:'icon-add',");
			sb.append("handler:"+function);
			sb.append("},");
		}
		sb.delete(sb.length() - 1, sb.length());
			sb.append("],");
		//has nothing ,then return "";
		if(sb.length()<20){sb.setLength(0);}
		String btnString = sb.toString();
		return btnString;
	}



	public A1TemplateTableDto getTemplateTable(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		A1TemplateTableDto templateTable = templateTable = templateService.getTemplateTable(keyRandom);
		return templateTable;
	}

	/**
	 * 取查询排序属性条件列表
	 * @return
	 * */
	/*@Deprecated
	public List<A1TemplateColumnDto> getSortColumnList(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		A1TemplateTableDto templateTable = getTemplateTable(keyRandom);
		List<A1TemplateColumnDto> a1TemplateColumnDtoRemoveList = new ArrayList<A1TemplateColumnDto>();
		List<A1TemplateColumnDto> a1TemplateColumnDtoList = templateTable.getA1TemplateColumnDtoList();
		for(A1TemplateColumnDto a1TemplateColumnDto : a1TemplateColumnDtoList){
			//不是排序属性
			if(a1TemplateColumnDto.getIsSortColumn() == 0){
				a1TemplateColumnDtoRemoveList.add(a1TemplateColumnDto);
				continue;
			}
		}
		a1TemplateColumnDtoList.removeAll(a1TemplateColumnDtoRemoveList);
		//页面上是<s:select> pagecontext不行，一定要session,原因不明
		pageContext.getSession().setAttribute("sortColumnList", a1TemplateColumnDtoList);

		return a1TemplateColumnDtoList;
	}*/



	/*public List<A1TemplateColumnDto> getSortColumnList(A1TemplateTableDto templateTable){
		List<A1TemplateColumnDto> a1TemplateColumnDtoRemoveList = new ArrayList<A1TemplateColumnDto>();
		List<A1TemplateColumnDto> a1TemplateColumnDtoList = templateTable.getA1TemplateColumnDtoList();
		for(A1TemplateColumnDto a1TemplateColumnDto : a1TemplateColumnDtoList){
			//不是排序属性
			if(a1TemplateColumnDto.getIsSortColumn() == 0){
				a1TemplateColumnDtoRemoveList.add(a1TemplateColumnDto);
				continue;
			}
		}
		a1TemplateColumnDtoList.removeAll(a1TemplateColumnDtoRemoveList);
		//页面上是<s:select> pagecontext不行，一定要session,原因不明
		//pageContext.getSession().setAttribute("sortColumnList", a1TemplateColumnDtoList);

		return a1TemplateColumnDtoList;
	}*/


	/*public Map<String, Object> getDatagridPropertyMultiQuery(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		return templateService.getConditionMultiQuery(keyRandom);
	}*/

	/*private List<A1TemplateRightMenuDto> getRightMenuList(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		A1TemplateTableDto templateTable = getTemplateTable(keyRandom);
		List<A1TemplateRightMenuDto> rightMenuDtoList = templateTable.getA1TemplateRightMenuDtoList();
		return rightMenuDtoList;
	}*/

	/*public A1TemplateTableDto getTemplateTable(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		pageContext.getSession().removeAttribute("templateTable"+keyRandom);
		A1TemplateTableDto templateTable = getTemplateTable(keyRandom);
		return templateTable;
	}*/


	/**
	 * 多值选择，key-value形式; case status when 1 then '有效' when 0 then '无效' end
	 * @param paramMap
	 * @return
	 */
	/*public String getTemplateTableColumnOptionJson(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		String jsonArrayColumnOptionsStr = templateService.getTemplateTableColumnOptionJson(keyRandom);
		return jsonArrayColumnOptionsStr;
	}*/

/*

	*/
/**
 * 多值选择，key-value形式; case status when 1 then '有效' when 0 then '无效' end
 * @param paramMap
 * @return
 *//*

	public List<A1TemplateColumnDto> getTemplateTableColumnOptionList(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		return templateService.getTemplateTableColumnOptionList(keyRandom);
	}

	public String getDatagridProperty(Map<String,String> paramMap){
		String keyRandom = paramMap.get("keyRandom");
		A1TemplateTableDto templateTable = getTemplateTable(keyRandom);
		List<A1TemplateConditionDto> conditionList = templateTable.getA1TemplateConditionDtoList();

		StringBuilder sb = new StringBuilder();
		for(A1TemplateConditionDto a1TemplateConditionDto:conditionList){
			String columnName = a1TemplateConditionDto.getColumnName();
			String columnShowName = a1TemplateConditionDto.getColumnShowName();
			sb.append(columnName).append(":'").append(columnShowName).append("',");
		}
		if(sb.length()>2)
			sb.delete(sb.length()-1,sb.length());
		return sb.toString();
	}
*/


}
